const express = require("express")
const router = express.Router()
const Account = require("../models/accounts")
const { log } = require("console")

router.post("/", async (req, res) => {
    try {
        const accountData = req.body
        const user = await Account.addAccount(accountData)
        if (user > 0) {
            res.status(200).json({ code: 200, message: "账户添加成功" })
        } else {
            res.status(500).json({ code: 500, message: "账户添加失败" })
        }
    } catch (error) {
        res.status(500).json({ code: 500, message: error.message })
    }
})

router.get("/", async (req, res) => {
    try {
        const accountData = req.query //获取用户名和密码
        const { token, account } = await Account.getAccount(accountData) //通过封装的方法获取token
        if (!token) {
            res.status(200).json({ code: 200, message: "用户名或密码错误" })
        } else {
            //将token存储到cookie里，防范XSS攻击
            res.cookie("token", token, {
                httpOnly: true,  // 防止客户端脚本访问 
                maxAge: 1000 * 60 * 60, // 1小时
                sameSite: "lax",// 防止跨站请求伪造（CSRF）
                secure: false,// 开发阶段使用 HTTP，生产环境使用 HTTPS
                path: "/" //固定路径
            })
            res.status(200).json({ code: 200, account: account, message: "登录成功" })
        }
    } catch (error) {
        res.status(500).json({ code: 500, message: error.message })
    }
})

router.put("/", async (req, res) => {
    try {
        const accountData = req.body
        const result = await Account.updateAccount(accountData)
        if (result > 0) {
            res.status(200).json({ code: 200, message: "账户更新成功" })
        } else {
            res.status(200).json({ code: 200, message: "账户未找到" })
        }
    } catch (error) {
        res.status(500).json({ code: 500, message: error.message })
    }
})

module.exports = router